import * as bajaService from '@/services/bajaService';
import { MODULE_TYPE, SUBSYSTEM_TYPE } from '@/utils/constants';

export default {
  namespace: 'subSystem',
  state: {
    $handle: '',
    $typeSpec: 'ibmsSupervisor:CommonSubSystem',
    title: '',
    subSystemType: 'url',
    navOrd: '',
    subModules: [],
    selectedModuleIndex: 0
  },
  reducers: {
    setData(state, { payload }) {
      return { ...state, ...payload};
    },
    setSelectedModuleIndex(state, {payload: {selectedModuleIndex}}) {
      return { ...state, selectedModuleIndex};
    }
  },
  effects: {
    *fetch({ payload: {subSystemOrd} }, { call, put }) {
      let $handle='', $typeSpec='', title='', subSystemType='url', navOrd='', subModules=[];
      const subSystem = yield call(bajaService.Ord, subSystemOrd);
      if(subSystem) {
        $handle = subSystem.$handle;
        $typeSpec = subSystem.getType().$typeSpec;
        title = subSystem.getTitle();
        const { $ordinal } =  subSystem.getSubSystemType();
        subSystemType = SUBSYSTEM_TYPE[$ordinal];
        navOrd = subSystem.getNavOrd().toString();
        const modulesRoot = yield call(bajaService.Ord, navOrd+'/modulesRoot');
        if(modulesRoot) {
          subModules = yield call(bajaService.fetchNavChildren, modulesRoot);
          if(subModules) {
            subModules = subModules.map(subModule=> {
              const { $ordinal } =  subModule.getModuleType();
              return ({
                $handle: subModule.$handle,
                $typeSpec: subModule.getType().$typeSpec,
                title: subModule.getTitle(),
                nIcon: subModule.getNIcon(),
                url: subModule.getUrl(),
                moduleType: MODULE_TYPE[$ordinal],
                pagePath: subModule.getPagePath(),
                navOrd: subModule.getNavOrd().toString()
              })
            });
          } else {
            subModules = []
          }
        }
      }
      yield put({ type: 'setData', payload: {
        $handle,
        $typeSpec,
        title,
        subSystemType,
        navOrd,
        subModules,
        selectedModuleIndex:0
      }});
    },
    *selectModule({ payload: {selectedModuleIndex} }, { put }) {
      yield put({ type: 'setSelectedModuleIndex', payload: {selectedModuleIndex}});
    }
  },

  // subscriptions: {
  //   setup({ dispatch, history }) {
  //     return history.listen(({ pathname }) => {
  //       const url = pathname.split("/");
  //       console.log("url", url);
  //       if (pathname.startsWith("/subSystem")) {
  //         // dispatch({ type: 'fetch', payload: {ord:'station:|h:'+url[2]}});
  //       }
  //     });
  //   },
  // },
}
